package com.itheima.controller;

import com.itheima.common.entity.Result;
import com.itheima.common.utils.POIUtils;
import com.itheima.pojo.OrderSetting;
import com.itheima.pojo.OrderSettingVO;
import com.itheima.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/ordersetting")
public class OrderSettingController {

    @Autowired
    private OrderSettingService orderSettingService;


    /**
     * 根据年月查询预约设置数据
     * @param month
     * @return
     */
    @GetMapping("/getOrderSettingByMonth")
    public Result findByYearMonth(String month) {
        List<OrderSettingVO> list = orderSettingService.findByYearMonth(month);
        return new Result(true, "获取预约设置数据成功",list);
    }


    /**
     * 根据日期修改可预约人数
     * @param orderSetting
     * @return
     */
    @PostMapping("/editNumberByOrderDate")
    public Result editNumberByOrderDate(@RequestBody OrderSetting orderSetting){
        orderSettingService.editNumberByOrderDate(orderSetting);
        return new Result(true, "预约设置成功");
    }

    @GetMapping("/download")
    public ResponseEntity<InputStreamResource> downloadTemplate(String filename) throws IOException {
        // 使用类加载器从资源目录加载文件
        ClassLoader classLoader = getClass().getClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream("templates/" + filename);

        // 检查文件是否存在
        if (inputStream == null) {
            throw new IOException("模板文件不存在: " + filename);
        }

        // 将数据写入输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        copyInputStreamToOutputStream(inputStream, outputStream);

        // 创建 InputStreamResource 以便进行下载
        InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(outputStream.toByteArray()));

        // 设置响应头，指定文件下载
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename);

        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }

    // 复制 InputStream 到 OutputStream 的方法
    private void copyInputStreamToOutputStream(InputStream inputStream, OutputStream outputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        inputStream.close();
    }


    @PostMapping("/upload")
    public ResponseEntity<Result> uploadExcel(MultipartFile excelFile) {
        // 检查文件是否为空
        if (excelFile.isEmpty()) {
            return ResponseEntity.ok(new Result(false, "文件为空，请选择一个文件上传。"));
        }

        try {
            // 调用工具类 POIUtils 解析 Excel 文件
            List<String[]> excelData = POIUtils.readExcel(excelFile);

            // 在这里处理解析的数据（例如：保存到数据库，打印到控制台等）
            processExcelData(excelData);


            return ResponseEntity.ok(new Result(true, "预约设置成功", null));

        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.ok(new Result(false, "文件解析失败：" + e.getMessage()));
        }
    }

    // 示例方法：处理解析后的 Excel 数据
    private void processExcelData(List<String[]> data) {
        // 处理 Excel 数据的逻辑（例如：保存到数据库）
        for (String[] row : data) {
            // 打印 Excel 每一行的数据
            System.out.println(String.join(", ", row));
        }
    }


}
